package cn.zyy.hotel.realm;

import cn.zyy.hotel.entity.Employee;
import cn.zyy.hotel.entity.Menu;
import cn.zyy.hotel.service.EmployeeService;
import cn.zyy.hotel.service.MenuService;
import cn.zyy.hotel.utils.ApplicationContextUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;
import java.util.Set;

public class EmployeeRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String principal = (String) principals.getPrimaryPrincipal();
        EmployeeService employeeService = (EmployeeService) ApplicationContextUtil.getBean("employeeServiceImpl");
        MenuService menuService = (MenuService) ApplicationContextUtil.getBean("menuServiceImpl");
        Employee employee = employeeService.login(principal);
        List<Menu> menuList = menuService.selectMenuListByEmployeeId(employee.getId());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if (menuList != null) {
            for (Menu menu : menuList) {
                if (menu.getPermissions() != null & !menu.getPermissions().isEmpty()) {
                    simpleAuthorizationInfo.addStringPermission(menu.getPermissions());
                }
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        EmployeeService employeeService = (EmployeeService) ApplicationContextUtil.getBean("employeeServiceImpl");
        Employee employee = employeeService.login(principal);
        if (employee != null) {
            return new SimpleAuthenticationInfo(employee.getLoginName(),employee.getLoginPwd(), ByteSource.Util.bytes(employee.getSalt()),this.getName());
        }
        return null;
    }
}
